package com.gm.wholesale.module.voice.voiceCreateOrder;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.ArrayMap;
import androidx.annotation.NonNull;
import com.gm.commonlib.base.baseBean.BaseListResp;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.wholesale.bluetooth.bean.WeightBean;
import com.gm.wholesale.cacheData.CacheData;
import com.gm.wholesale.constant.Constant;
import com.gm.wholesale.constant.Unit;
import com.gm.wholesale.module.custom.ChoiceCustomData;
import com.gm.wholesale.module.custom.bean.CustomBean;
import com.gm.wholesale.module.good.bean.GoodBean;
import com.gm.wholesale.module.good.model.GoodModel;
import com.gm.wholesale.module.order.bean.OrderRecmPriceBean;
import com.gm.wholesale.module.order.model.OrderModel;
import com.gm.wholesale.module.voice.IVoiceListener;
import com.gm.wholesale.module.voice.VoiceManger;
import com.gm.wholesale.module.voice.bean.VoiceGetGoodBean;
import com.gm.wholesale.module.voice.model.VoiceModel;
import com.gm.wholesale.util.Utils;

public class VoiceCreateOrderManger {

    private static VoiceCreateOrderManger manger;
    private static final int LOOP_TIME = 1000;

    public static VoiceCreateOrderManger newInstance() {
        if (manger == null) {
            manger = new VoiceCreateOrderManger();
        }
        return manger;
    }

    public interface OnVoiceCreateOrderListener {
        void createOrder(GoodBean goodBean);

        void showCreateOrderView(GoodBean goodBean);

        void onFinish(String text);
    }

    private OnVoiceCreateOrderListener mListener;

    public void setOnVoiceCreateOrderListener(OnVoiceCreateOrderListener listener) {
        mListener = listener;
    }

    private boolean mIsStart;
    private WeightBean mWeightBean;

    private GoodBean mGood;


    public void setWeightBean(WeightBean weightBean) {
        mWeightBean = weightBean;
    }

    //todo 根据语音去商品库查询商品
    private void getGoodByVoice(String goodName) {
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("text", goodName);
        VoiceModel.getGoodByVoice(null, queryData, new BaseHttpObserver<DataResp<VoiceGetGoodBean>>() {
            @Override
            protected void handleResultOkResp(DataResp<VoiceGetGoodBean> resp) {
                if (resp == null || resp.getData() == null
                        || resp.getData().getItems() == null
                        || resp.getData().getItems().isEmpty()) {
                    //有重量的话，才去数据库获取商品信息和价格，不然直接跳创建订单界面
                    //没有重量，必定跳创建订单界面去，那个界面会通过名字掉接口查询商品
                    //这里就没有必要重复查询了
                    if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                        getGoodByName(goodName);
                    } else {
                        createOrder();
                    }

                } else {
                    //todo 接口解析出数据，创建订单
                    createOrderByFindGood(resp.getData().getItems().get(0));
                }
            }

            @Override
            protected void handleResultOtherResp(DataResp<VoiceGetGoodBean> resp) {
                if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                    getGoodByName(goodName);
                } else {
                    createOrder();
                }
            }

            @Override
            protected void onError(String error) {
                if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                    getGoodByName(goodName);
                } else {
                    createOrder();
                }
            }
        });
    }

    // todo 通过语音调用接口解析数据，没有解析出来，则通过名字查询商品详情
    private void getGoodByName(String goodName) {
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("name", goodName);
        GoodModel.getSearchGood(null, queryData, new BaseHttpObserver<BaseListResp<GoodBean>>() {
            @Override
            protected void handleResultOkResp(BaseListResp<GoodBean> resp) {
                if (resp.getDatas() != null && !resp.getDatas().isEmpty()) {
                    //todo 设置里面关闭填入价格得话，把商品里面价格置空（查询商品时候，商品默认带有价格，需要移除）
                    mGood = resp.getDatas().get(0);
                    if (!CacheData.getIsAutoInputPrice()) {
                        mGood.setPrice(0);
                    }
                    else {
                        //获取斤单位的价格，填入
                        mGood.setPrice(mGood.getPriceByJin());
                    }
                } else {
                    mGood.setPrice(0);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
                //todo 用戶打開自動录入价格才去获取价格
                if (mGood.getId() > 0 && CacheData.getIsAutoInputPrice()) {
                    getGoodPrice(mGood.getId());
                } else {
                    if (mListener != null) {
                        createOrder();
                    }
                }

            }
        });
    }


    private void getGoodPrice(long goodId) {
        CustomBean customBean = ChoiceCustomData.newInstance().getCustomBean();
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        if (customBean != null) {
            queryData.put("customerID", customBean.getId());
            queryData.put("skuID", goodId);
            OrderModel.getOrderRecPrice(null, queryData, new BaseHttpObserver<>() {
                @Override
                protected void handleResultOkResp(DataResp<OrderRecmPriceBean> resp) {
                    if (resp != null && resp.getData() != null) {
                        setGoodPrice(resp.getData());
                    }
                }

                @Override
                public void onComplete() {
                    if (mListener != null) {
                        createOrder();
                    }
                }
            });
        }
    }

    private void setGoodPrice(OrderRecmPriceBean orderRecPriceBean) {
        double price = Utils.getOrderRecmPrice(orderRecPriceBean);
        if (mGood != null && price > 0 && CacheData.getIsAutoInputPrice()) {
            mGood.setPrice(price);
        }
    }


    //todo 在后端获取到数据
    private void createOrderByFindGood(VoiceGetGoodBean.ItemsDTO good) {
       Popupwindow.hiddenPop();
        if (good != null) {
            mGood = new GoodBean();
            mGood.setIsVoiceCreate(true);
            mGood.setId(good.getSkuId());
            mGood.setName(good.getSkuName());
            //货物单位
            if (!TextUtils.isEmpty(good.getUnitName())) {
                mGood.setUnitName(good.getUnitName());
            } else {
                mGood.setUnitName(Constant.DEFAULT_UNIT);
            }
            //获取价格
            if (!TextUtils.isEmpty(good.getUnitPrice())) {
                double price = Double.parseDouble(good.getUnitPrice());
                if (price > 0) {
                    mGood.setPrice(price);
                } else {
                    mGood.setPrice(0);
                }
            } else {
                mGood.setPrice(0);
            }
            //货物数量
            if (!TextUtils.isEmpty(good.getQuantity()) && Double.parseDouble(good.getQuantity()) > 0) {
                mGood.setGoodNum(Double.parseDouble(good.getQuantity()));
            } else {
                if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                    double num = Unit.getWeight(mWeightBean.getsUnit(), mGood.getUnitName(), mWeightBean.getWeightNum());
                    mGood.setGoodNum(num);
                }
            }
        }
        if (mGood.getGoodNum() > 0) { //直接创建单子
            if (mListener == null) return;
            mListener.createOrder(mGood);
        } else { //到创建订单界面，用户可以修改单子
            if (mListener == null) return;
            mListener.showCreateOrderView(mGood);
        }
        //停止录音
        stop();


    }


    //todo 异常或者接口没有 找到数据，直接使用语音解析的文字的创建订单
    private void createOrder() {
        Popupwindow.hiddenPop();
        mGood.setIsVoiceCreate(true);
        if (mListener == null) {
            stop();
            return;
        }
        //商品没有重量，到创建订单页面
        if (mWeightBean == null || mWeightBean.getWeightNum() <= 0) {
            mListener.showCreateOrderView(mGood);
        } else {
            // todo 语音录单默认使用斤
            mGood.setUnitName(Constant.DEFAULT_UNIT);
            double num = Unit.getWeight(mWeightBean.getsUnit(), Constant.DEFAULT_UNIT, mWeightBean.getWeightNum());
            mGood.setGoodNum(num);

            mListener.createOrder(mGood);
            mWeightBean = null;
        }
        stop();


    }

    public void start(Context context, OnVoiceCreateOrderListener listener) {
        mIsStart = true;
        startVoice(context);
        mListener = listener;


    }

    public void stop() {
        onFinish("");
        VoiceManger.stop();
        mListener = null;
        mIsStart = false;
        mContext = null;
        mWeightBean = null;
        if (handler != null) {
            handler.removeCallbacks(null);
        }
        handler = null;
        manger = null;

    }

    private Context mContext;

    public void startVoice(Context context) {

        mContext = context;
        mGood = null;
//        mGood = new GoodBean();
//        mGood.setName("土");
//        getGoodByVoice("土");
//        mWeightBean=new WeightBean();
//        mWeightBean.setWeight("22");
//        mWeightBean.setsUnit("斤");
        VoiceManger.startVoice(context, new IVoiceListener() {
            @Override
            public void onVolumeChanged() {

            }

            @Override
            public void onEndOfSpeech() {
                loopVoice();

            }

            @Override
            public void onResult(String text) {
                if (!TextUtils.isEmpty(text)) {
                    mIsStart = false;
                    mGood = null;
                    mGood = new GoodBean();
                    mGood.setName(text);
                    getGoodByVoice(text);
                }

            }

            @Override
            public void onError(String error) {
                loopVoice();

            }
        });
    }

    private void onFinish(String error) {
        if (mListener != null) {
            mListener.onFinish(error);
        }
    }

    private synchronized void loopVoice() {
        if (handler != null) {
            handler.sendEmptyMessageAtTime(1, LOOP_TIME);
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (!mIsStart) return;
            startVoice(mContext);
        }
    };


}
